package com.ta.service.impl;

import com.ta.mapper.ProductMapper;
import com.ta.pojo.Product;
import com.ta.service.ProductService;
import com.ta.service.ex.ProductNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ProductImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${product.weight}")
    private String productWeight;

    /*初始化热销榜*/


    /**
     * 实现热销榜业务接口
     * @return
     */
    @Override
    public List<Product> findByPriority() {
        if (redisTemplate.opsForZSet().zCard(productWeight).equals(0L)) {
            List<Product> products = productMapper.findByAll();
            Set<ZSetOperations.TypedTuple<Product>> set = new HashSet<>();
            for (Product product : products) {
                ZSetOperations.TypedTuple<Product> typedTuple = new DefaultTypedTuple<>(product, product.getPriority().doubleValue());
                set.add(typedTuple);
            }
            redisTemplate.opsForZSet().add(productWeight, set);
        }

        Set<Product> set = redisTemplate.opsForZSet().reverseRange(productWeight,0,9);
        return new ArrayList<Product>(set);
    }

    /**
     * 实现最新榜业务接口
     * @return
     */
    @Override
    public List<Product> findByTime() {
        return productMapper.findByTime();
    }

    /**
     * 实现商品详情业务
     * @param id
     * @return
     */
    @Override
    public Product finyById(Integer id) {
        Product product = productMapper.finById(id);
        if (product == null) {
            throw new ProductNotFoundException("该商品已下架！");
        }
        return product;
    }
}
